package Servlets;

import java.sql.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
	
	Connection conn;
	ResultSet res;
	
	String MyUsername, MyPassword, MyNickname, query; 
	
	DatabaseConnection dbconn;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() 
    {
    	
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		processRequest(request, response);	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		//System.out.println("my post");
		processRequest(request, response);
	}

	protected void processRequest(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException 
	{
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		
		try
		{
			MyUsername = request.getParameter("username");
			MyPassword = request.getParameter("password");
			//MyNickname = request.getParameter("nickname");
			
			query = "INSERT INTO Users (username, password, nickname) VALUES ('" + MyUsername + "','" + MyPassword + "','" + MyNickname + "');";
			dbconn = new DatabaseConnection();			
			conn = dbconn.setConnection();
			
			 Statement st=conn.createStatement();
	           ResultSet rs=st.executeQuery("select * from users where username='"+MyUsername+"' and password='"+MyPassword+"'");
	           int count=0;
	           while(rs.next()){
	           count++;
	          }
	          if(count>0){
	        	  response.sendRedirect("WaitingRoom.jsp");
	           }
	          else{
	           response.sendRedirect("MainPage.jsp");
	          }
		
		}
		catch (Exception e)
		{
			System.out.println(e);
		}
		finally
		{
			out.close();
		}
/*		
		try 
		{
		     res.close();
		     conn.close();
		} 
		catch (Exception e)
		{
		     e.printStackTrace();
		}
	*/	
		
	}
	
	

}
